package com.yudi.blog.bussiness.controller;

import com.yudi.blog.bussiness.dto.Comment;
import com.yudi.blog.bussiness.dto.User;
import com.yudi.blog.bussiness.service.BlogService;
import com.yudi.blog.bussiness.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpSession;

/**
 * @Author YuDi
 * @Date 2021/11/14 21:33
 * @Version 1.0
 */
@Controller
public class CommentController {

    @Autowired
    private CommentService commentService;

    @Autowired
    private BlogService blogService;


    @Value("${comment.avatar}")
    private String avatar;

    @GetMapping("/comments/{id}")
    public String comments(@PathVariable Long id, Model model){

        model.addAttribute("comments",commentService.listCommentByBlogId(id));
        return "blog :: commentList";
    }


    @PostMapping("/comments")
    public String post(Comment comment, HttpSession httpSession){
        User user = (User) httpSession.getAttribute("user");
        if(user != null){
            comment.setAvatar(user.getAvatar());
            comment.setAdminComment(true);
        } else {
            comment.setAvatar(avatar);
        }

        comment.setBlog(blogService.getBlog(comment.getBlog().getId()));
        commentService.save(comment);
        return "redirect:/comments/"+comment.getBlog().getId();
    }

}
